import { ElMessage, ElNotification } from 'element-plus'
import { imageApi } from '@/api/image'
import { textApi } from '@/api/text'
import { aiApi } from '@/api/ai'

/**
 * 集成测试工具
 * 测试前后端接口的实际连接和功能
 */
export class IntegrationTest {
  private baseUrl = 'http://localhost:8080/api'
  
  /**
   * 运行完整的集成测试
   */
  async runIntegrationTests(): Promise<{
    success: boolean
    results: Array<{
      name: string
      status: 'success' | 'error'
      message: string
      duration: number
    }>
  }> {
    const results: Array<{
      name: string
      status: 'success' | 'error'
      message: string
      duration: number
    }> = []

    console.log('🚀 开始运行集成测试...')

    // 测试后端连接
    const backendTest = await this.testBackendConnection()
    results.push(backendTest)

    // 测试图片上传API
    const uploadTest = await this.testImageUploadAPI()
    results.push(uploadTest)

    // 测试图片列表API
    const listTest = await this.testImageListAPI()
    results.push(listTest)

    // 测试搜索API
    const searchTest = await this.testSearchAPI()
    results.push(searchTest)

    // 测试AI识别API
    const aiTest = await this.testAIRecognitionAPI()
    results.push(aiTest)

    // 测试文案生成API
    const textGenTest = await this.testTextGenerationAPI()
    results.push(textGenTest)

    // 测试图片扩展API
    const expandTest = await this.testImageExpansionAPI()
    results.push(expandTest)

    const successCount = results.filter(r => r.status === 'success').length
    const success = successCount === results.length

    console.log(`✅ 集成测试完成: ${successCount}/${results.length} 通过`)

    return { success, results }
  }

  /**
   * 测试后端连接
   */
  private async testBackendConnection(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const response = await fetch(`${this.baseUrl}/health`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.ok) {
        return {
          name: '后端连接测试',
          status: 'success',
          message: '后端服务连接正常',
          duration: Date.now() - startTime
        }
      } else {
        return {
          name: '后端连接测试',
          status: 'error',
          message: `后端服务响应异常: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '后端连接测试',
        status: 'error',
        message: `后端服务连接失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试图片上传API
   */
  private async testImageUploadAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      // 创建测试图片文件
      const testFile = this.createTestImageFile()
      const formData = new FormData()
      formData.append('file', testFile)

      const response = await fetch(`${this.baseUrl}/images/upload`, {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data) {
          return {
            name: '图片上传API测试',
            status: 'success',
            message: '图片上传功能正常',
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: '图片上传API测试',
            status: 'error',
            message: '上传响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: '图片上传API测试',
          status: 'error',
          message: `上传请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '图片上传API测试',
        status: 'error',
        message: `上传测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试图片列表API
   */
  private async testImageListAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const response = await fetch(`${this.baseUrl}/images?page=0&size=10`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && Array.isArray(data.data.content)) {
          return {
            name: '图片列表API测试',
            status: 'success',
            message: `获取到 ${data.data.content.length} 张图片`,
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: '图片列表API测试',
            status: 'error',
            message: '列表响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: '图片列表API测试',
          status: 'error',
          message: `列表请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '图片列表API测试',
        status: 'error',
        message: `列表测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试搜索API
   */
  private async testSearchAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const response = await fetch(`${this.baseUrl}/images/search?keyword=test&page=0&size=10`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && Array.isArray(data.data.content)) {
          return {
            name: '搜索API测试',
            status: 'success',
            message: `搜索功能正常，找到 ${data.data.content.length} 个结果`,
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: '搜索API测试',
            status: 'error',
            message: '搜索响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: '搜索API测试',
          status: 'error',
          message: `搜索请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '搜索API测试',
        status: 'error',
        message: `搜索测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试AI识别API
   */
  private async testAIRecognitionAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const testFile = this.createTestImageFile()
      const formData = new FormData()
      formData.append('file', testFile)

      const response = await fetch(`${this.baseUrl}/ai/recognize`, {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data && Array.isArray(data.data.tags)) {
          return {
            name: 'AI识别API测试',
            status: 'success',
            message: `AI识别正常，识别出 ${data.data.tags.length} 个标签`,
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: 'AI识别API测试',
            status: 'error',
            message: 'AI识别响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: 'AI识别API测试',
          status: 'error',
          message: `AI识别请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: 'AI识别API测试',
        status: 'error',
        message: `AI识别测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试文案生成API
   */
  private async testTextGenerationAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const requestBody = {
        imageId: 1,
        type: 'short',
        style: 'creative'
      }

      const response = await fetch(`${this.baseUrl}/ai/generate-text`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data && data.data.content) {
          return {
            name: '文案生成API测试',
            status: 'success',
            message: `文案生成正常，生成内容长度: ${data.data.content.length}`,
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: '文案生成API测试',
            status: 'error',
            message: '文案生成响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: '文案生成API测试',
          status: 'error',
          message: `文案生成请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '文案生成API测试',
        status: 'error',
        message: `文案生成测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 测试图片扩展API
   */
  private async testImageExpansionAPI(): Promise<{
    name: string
    status: 'success' | 'error'
    message: string
    duration: number
  }> {
    const startTime = Date.now()
    
    try {
      const requestBody = {
        imageId: 1,
        count: 3,
        style: 'similar'
      }

      const response = await fetch(`${this.baseUrl}/ai/expand-image`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      })

      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data && Array.isArray(data.data.images)) {
          return {
            name: '图片扩展API测试',
            status: 'success',
            message: `图片扩展正常，生成 ${data.data.images.length} 张图片`,
            duration: Date.now() - startTime
          }
        } else {
          return {
            name: '图片扩展API测试',
            status: 'error',
            message: '图片扩展响应数据格式异常',
            duration: Date.now() - startTime
          }
        }
      } else {
        return {
          name: '图片扩展API测试',
          status: 'error',
          message: `图片扩展请求失败: ${response.status}`,
          duration: Date.now() - startTime
        }
      }
    } catch (error) {
      return {
        name: '图片扩展API测试',
        status: 'error',
        message: `图片扩展测试失败: ${error instanceof Error ? error.message : '未知错误'}`,
        duration: Date.now() - startTime
      }
    }
  }

  /**
   * 创建测试用的图片文件
   */
  private createTestImageFile(): File {
    // 创建一个1x1像素的透明PNG图片的base64数据
    const base64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
    const byteCharacters = atob(base64Data)
    const byteNumbers = new Array(byteCharacters.length)
    
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
    }
    
    const byteArray = new Uint8Array(byteNumbers)
    return new File([byteArray], 'test-image.png', { type: 'image/png' })
  }

  /**
   * 测试数据库连接
   */
  async testDatabaseConnection(): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseUrl}/health/db`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      return response.ok
    } catch (error) {
      console.error('数据库连接测试失败:', error)
      return false
    }
  }

  /**
   * 测试AI服务连接
   */
  async testAIServiceConnection(): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseUrl}/health/ai`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      return response.ok
    } catch (error) {
      console.error('AI服务连接测试失败:', error)
      return false
    }
  }
}

// 导出集成测试实例
export const integrationTest = new IntegrationTest()